﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace BackgroundTaskLib.TestUI
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private readonly Random rng = new Random();

        public MainWindow()
        {
            TaskManager = new TaskManager();
            ViewModel = new TaskManagerViewModel(TaskManager);

            InitializeComponent();

            TaskManager.Queue(new BackgroundTask(TestTaskCreator, "Test Task Creator"));
        }

        private TaskManager TaskManager { get; set; }
        public TaskManagerViewModel ViewModel { get; private set; }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            var parent = TaskManager.Queue(new BackgroundTask(x => TestTask(rng.Next(500, 2000), rng.Next(1, 60), x), "Parent Task"));
            TaskManager.QueueAfter(parent, new BackgroundTask(x => TestTask(rng.Next(500, 2000), rng.Next(1, 60), x), "Child Task"));
        }

        private void TestTaskCreator(Func<double, string, bool> progressAction)
        {
            progressAction(-1, null);

            while (true)
            {
                Thread.Sleep(rng.Next(1000, 30000));

                TaskManager.Queue(new BackgroundTask(x => TestTask(rng.Next(500, 2000), rng.Next(1, 60), x), "Test Task"));
            }
        }

        private void TestTask(int wait, int count, Func<double, string, bool> progressAction)
        {
            Debug.WriteLine("TestTask: {0}x {1} ms", count, wait);

            for (var i = 0; i < count; ++i)
            {
                Thread.Sleep(wait);

                if (progressAction((double)i / count, null))
                {
                    break;
                }
            }
        }
    }
}
